package com.yanchangapp.ui.activity.purchase.contract;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.PsDetailProductAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.OrderProductBean;
import com.yanchangapp.model.response.ContractDetailResponse;
import com.yanchangapp.ui.activity.purchase.POrderListActivity;
import com.yanchangapp.ui.presenter.ContractEnsureAtPresenter;
import com.yanchangapp.ui.view.ContractEnsureAtView;
import com.yanchangapp.widget.DelayShowDialog;
import com.yanchangapp.widget.SpannableMoney;
import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.NiceNestedScrollView;
import com.zxl.baselib.widget.TipDialog;
import com.zxl.baselib.widget.YCLoadingView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 合同确认的活动...
 */
public class ContractEnsureActivity extends BaseActivity<ContractEnsureAtView, ContractEnsureAtPresenter> implements ContractEnsureAtView {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ibAddMenu)
    ImageButton ibAddMenu;
    @BindView(R.id.btnApprove)
    Button btnApprove;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.tvOrderContractTitle)
    TextView tvOrderContractTitle;
    @BindView(R.id.tvOrderContract)
    TextView tvOrderContract;
    @BindView(R.id.tvSignTimeTitle)
    TextView tvSignTimeTitle;
    @BindView(R.id.tvSignTime)
    TextView tvSignTime;
    @BindView(R.id.tvBuyerTitle)
    TextView tvBuyerTitle;
    @BindView(R.id.tvBuyerName)
    TextView tvBuyerName;
    @BindView(R.id.tvBuyerNoTitle)
    TextView tvBuyerNoTitle;
    @BindView(R.id.tvBuyerNo)
    TextView tvBuyerNo;
    @BindView(R.id.tvBuyerBankTitle)
    TextView tvBuyerBankTitle;
    @BindView(R.id.tvBuyerBank)
    TextView tvBuyerBank;
    @BindView(R.id.tvSupplierTitle)
    TextView tvSupplierTitle;
    @BindView(R.id.tvSupplierName)
    TextView tvSupplierName;
    @BindView(R.id.tvSupplierNoTitle)
    TextView tvSupplierNoTitle;
    @BindView(R.id.tvSupplierNoName)
    TextView tvSupplierNoName;
    @BindView(R.id.tvSupplierBankTitle)
    TextView tvSupplierBankTitle;
    @BindView(R.id.tvSupplierBankName)
    TextView tvSupplierBankName;
    @BindView(R.id.rvOrderDetail)
    RecyclerView rvOrderDetail;
    @BindView(R.id.tvTitleStartTime)
    TextView tvTitleStartTime;
    @BindView(R.id.ivStartArrow)
    ImageView ivStartArrow;
    @BindView(R.id.rlClause)
    RelativeLayout rlClause;
    @BindView(R.id.scrollContent)
    NiceNestedScrollView scrollContent;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    private String id;
    private static final String ID = "id";

    private List<OrderProductBean> mOrderProductBeans = new ArrayList<>();
    private PsDetailProductAdapter mPsDetailProductAdapter;
    // 合同条款字符串信息
    private String clause;
    private DelayShowDialog mDelayShowDialog;
    private TipDialog mQuitDialog;

    @Override
    protected void init() {
        if (getIntent() != null){
            id = getIntent().getStringExtra(ID);
        }
    }

    public static void show(Activity activity, String id) {
        Intent intent = new Intent(activity, ContractEnsureActivity.class);
        intent.putExtra(ID, id);
        activity.startActivity(intent);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_contract_ensure;
    }

    @Override
    protected ContractEnsureAtPresenter createPresenter() {
        return new ContractEnsureAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ivToolbarNavigation.setVisibility(View.INVISIBLE);
        tvToolbarTitle.setText("确认采购合同");
        ibAddMenu.setImageResource(R.mipmap.ic_toolbar_close);
        ibAddMenu.setVisibility(View.VISIBLE);
        initAdapter();
    }

    private void initAdapter() {
        // 设置商品的Adapter
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvOrderDetail.setHasFixedSize(true);
        rvOrderDetail.setNestedScrollingEnabled(false);
        rvOrderDetail.setLayoutManager(manager);
        rvOrderDetail.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this, 0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mPsDetailProductAdapter = new PsDetailProductAdapter(R.layout.item_order_product_detail, mOrderProductBeans);
        rvOrderDetail.setAdapter(mPsDetailProductAdapter);
    }

    @Override
    protected void initData() {
        setLoadingState(LoadingType.LOADING);
        mPresenter.queryContractDetail(id);
    }

    private void setLoadingState(LoadingType loadingType){
        switch (loadingType){
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE){
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:

                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.GONE){
                    scrollContent.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollContent.getVisibility() == View.VISIBLE){
                    scrollContent.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.GONE){
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void initListener() {
        ibAddMenu.setOnClickListener(v -> showQuitDialog());

        btnNextRefresh.setOnClickListener(v -> initData());

        btnApprove.setOnClickListener(v -> mPresenter.submitApprove(id));

        rlClause.setOnClickListener(v -> {
            // 展示clause信息
            ContractClauseActivity.show(ContractEnsureActivity.this,clause);
        });
    }

    @Override
    public void getContractDetailSuccess(ContractDetailResponse contractDetailResponse) {
        setLoadingState(LoadingType.SUCCESS);
        // 设置基本信息 用户等
        tvSignTime.setText(TimeUtil.getDayTime(contractDetailResponse.getCreateDate()));
        tvOrderContract.setText(contractDetailResponse.getInvoiceNo());
        tvBuyerName.setText(contractDetailResponse.getPurName());
        tvBuyerNo.setText(contractDetailResponse.getPurBankno());
        tvBuyerBank.setText(contractDetailResponse.getPurBank());
        tvSupplierName.setText(contractDetailResponse.getSupName());
        tvSupplierNoName.setText(contractDetailResponse.getSupBankno());
        tvSupplierBankName.setText(contractDetailResponse.getSupBank());
        // 底部商品数量以及价格
        String totalMoney = BigDecimalUtils.keep2Decimal(contractDetailResponse.getTotalMoney());
        int len = totalMoney.length();
        SpannableString spannableString = new SpannableString(
                ResHelper.getString(R.string.down_order_sum,String.valueOf(contractDetailResponse.getProducts().size()),totalMoney));
        int totalLength = spannableString.length();
        spannableString.setSpan(new SpannableMoney(ContractEnsureActivity.this),
                totalLength-len-1,totalLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvProductSum.setText(spannableString);
        // 合同明细
        if (contractDetailResponse.getProducts() != null){
            mOrderProductBeans.clear();
            mOrderProductBeans.addAll(contractDetailResponse.getProducts());
            mPsDetailProductAdapter.notifyDataSetChanged();
        }
        // 合同条款信息
        clause = contractDetailResponse.getCovenant();
    }

    // 延迟2秒执行
    private void showSecondsBack(){
        showDelayDialog();
        UIUtils.postTaskDelay(new Runnable() {
            @Override
            public void run() {
                hideDelayDialog();
                reBackToListAndRefresh();
            }
        },2000);
    }

    /**
     * 返回列表,并通知刷新
     */
    private void reBackToListAndRefresh(){
        mRxManager.post(ContractListActivity.REFRESH_CONTRACT_LIST,true);
        reBackToList();
    }

    private void  showDelayDialog(){
        if (null == mDelayShowDialog){
            mDelayShowDialog = new DelayShowDialog(this);
        }
        mDelayShowDialog.show();
    }

    private void hideDelayDialog(){
        mDelayShowDialog.hide();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showQuitDialog(){
        if (mQuitDialog == null){
            mQuitDialog = new TipDialog.Builder(this)
                    .setMessage("合同暂未提交,确定退出？")
                    .setEnsureClickListener(new TipDialog.EnsureClickListener() {
                        @Override
                        public void onEnsureClick(TipDialog tipDialog) {
                            tipDialog.dismiss();
                            reBackToList();
                        }
                    }).build();
        }
        mQuitDialog.show();
    }

    /**
     * 返回列表
     */
    private void reBackToList(){
        AppManager.getAppManager().returnToActivity(ContractListActivity.class);
    }

    @Override
    public void getContractDetailFailure(String err) {
        setLoadingState(LoadingType.ERROR);
        UIUtils.showToast(err);
    }

    @Override
    public void submitApproveSuccess() {
        // 提交审批成功
        showSecondsBack();
    }

    @Override
    public void submitApproveFailure(String err) {
        // 失败
        UIUtils.showToast(err);
    }
}
